<?
/**
 * VoiceOne Settings/Numbers/edit
 *
 * Frontend to provide access to the numbering system in voiceone.
 * @package voiceone
 * @subpackage  settings_number
 */
 
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  sajax_init();
  
  //================ XAJAX ================
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $id=$formData["id"];
    $name=$formData["name"];
    $numberArr=$formData["phonenumber"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all providers
    $dpArr=$asterisk->getPhoneNumber(0);
    if(is_array($dpArr)){
      foreach($dpArr as $dp) {
        if($id!=$dp["id"]) $dpNameArr[]=$dp["name"];
      }
    }
    // Check Name ((not null)&&(unique))
    $nameErr=false;
    if($name=="") { 
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;  
    }else if((is_array($dpNameArr))&&(in_array($name,$dpNameArr))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check numbers (not null)
    $numbErr=false;
    if(!(is_array($numberArr))) { 
      //Array numbers cannot be empty
      $errOut[]= T_("Dial pattern must have almost one pattern");
      $objResponse->addAssign("numbErr","innerHTML",$imgErr);
      $numbErr=true;  
    }else{
      foreach($numberArr as $numb){
        if(trim($numb)==""){
          //Array numbers cannot be empty
          $errOut[]= T_("Dial pattern cannot contain empty pattern");
          $objResponse->addAssign("numbErr","innerHTML",$imgErr);
          $numbErr=true; 
          break;
        }
      }
    }
    if($numbErr===false) $objResponse->addAssign("numbErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML",""); 
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();

  //=================== POST ====================
  if (count($_POST)>0) {
    $entry=Array(
      "name"      => $_POST["name"],
      "number"    => Array(),
      "emergency" => 0,
      "groups"    => $_POST["group"] 
    );
    if (is_array($_POST["phonenumber"])) { 
      foreach($_POST["phonenumber"] as $pn) $entry["number"][]=trim($pn);
    }
    //If modify existing one, set id
    if (isset($_POST["id"])) $entry["id"]=$_POST["id"];
    //Put dial pattern
    $ret=$asterisk->putPhoneNumber($entry);
    if ($ret>0) {
      $alert="<div class=\"AlertGood\">".T_("The Dial Pattern has been modified")."</div>";
      $_GET["id"]=$ret;
    } 
    else $alert="<div class=\"AlertBad\">".T_("The Dial Pattern hasn't been modified")."</div>";
    goToMainPage($alert);
  }
  
  //================ PAGE LOGIC ================
  //Get dial pattern informations
  if((isset($_GET["id"]))&&($_GET["id"]!="")) {
    $ret=$asterisk->getPhoneNumber($_GET["id"]);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $name=$v["name"];
    $groups=$v["groups"];
    //retrieve the phone numbers
    if (is_array($v["number"])) {
      foreach($v["number"] as $e) $numbers.="<option value='$e'>$e</option>";
    }
    $title=sprintf(T_("Modify Dial Pattern \"%s\""),$name );
  }
  else $title=T_("Edit new Dial Pattern");
  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/"); 
  ?>
  <?$sel="dialpattern";include("../../navigation.php");?>
  
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin" ><?=T_("Return without save")?></a>
    </h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post" onSubmit="return selectAll(getElementById('phonenumber'))">      
    	<h2><?=T_("Dial Patterns")?></h2>
      <p class="blockintro"><?=T_("List below the dial patterns")?></p>
      <!-- DIAL PATTERN -->
      <div class="block">
        <table>
          <!-- Name Section -->
          <tr><td class="required" colspan="2"><label for="name"><?=T_("Dial pattern name")?>:</label></td></tr>
          <tr><td colspan="2"><input type="text" size="25" maxlength="100" id="name" name="name" value="<?=$name?>" /> <span id="nameErr"></span> <span class="help"><?=T_("I.e. toll-free, mobile phone, etc...")?></span></td></tr>
          <!-- Number section -->
          <tr>
            <td class="required"><label for="number"><?=T_("Dial Pattern")?>:</label></td>
            <td class="required"><?=T_("Added Dial Pattern")?></td>
          </tr>
          <tr>
            <td valign="top">
              <input type="text" size="25" maxlength="100" id="number" name="number" value="" />
              <input type="button" value="+" onclick="addOption(getElementById('phonenumber'),document.getElementById('number').value); document.getElementById('number').value='';" title="Add Length">
            </td>
            <td>
              <select name="phonenumber[]" size="4" onchange="saved = false" ondblclick="editOptions(this)" multiple style="float: left" id="phonenumber">
                <?=$numbers?>
              </select>
              <input type="button" value="edit" onclick="editOptions(getElementById('phonenumber'))" title="Edit Length(s)">
              <input type="button" value="X" onclick="deleteOptions(getElementById('phonenumber'))" title="Delete Length(s)">
              <span id="numbErr"></span> 
            </td>
          </tr>
        </table>
      </div>
    <!-- GROUPS -->
    <? echo listGroup(GROUP_OF_PHONENUMBER, $js, $groups);?>      
    <!-- INPUT BUTTONS -->
    <div class="action">
      <?if (isset($_GET["id"])) {?><input type="hidden" id="id" name="id" value="<?=$id?>" /><?}?>
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" selectAll(getElementById('phonenumber')); document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
    <!--
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" />
    -->
    </div>
  </form>
 </div>  
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
        <div class="Sidebar">
          <h1><?=T_("Informations")?></h1>
          <?=T_("<p>A phone number can be specified by a simple list of digit or by an regular expression.</p>
                <p>These are some regular expression symbols:</p>
                <ol>
                <li>_ :start of a regular expression</li>
                <li>N :indicate a number between 2 and 9</li>
                <li>X :any digit</li>
                <li>[xxx] :optional digit</li>
                </ol>")?>



<!--
                 <p>A phone number can be specified by a simple list of digit or by an regular expression.</p>".
                "          <p>These are some regular expression symbols:</p>".
                "          <ol>".
                "            <li>_ :start of a regular expression</li>".
                "            <li>N :indicate a number between 2 and 9</li>".
                "            <li>X :any digit</li>".
                "            <li>[xxx] :optional digit</li>".
                "          </ol>";
-->

        </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "rules");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>
